<?php
    //提交修改数据
    if(!empty($_POST)){

        $id=$_POST['id'];
        $pid=$_POST['pid'];
        $name=$_POST['name'];
        if($id==$pid){

            $sql="update `cate` set `name`='$name' where `id`=$id";
        }else{
            $sql="update `cate` set `pid`='$pid',`name`='$name' where `id`=$id";
        }
        mysqli_query($link,$sql);
        $result=mysqli_affected_rows($link);
        if($result>0){
            echo '<script>alert("新闻修改成功");location.href="index.php?c=cate&a=list&admin=1";</script>';die;
        }else{
            echo '<script>alert("新闻修改失败");history.go(-1);</script>';die;
        }
    }



    //ajax获取下拉列表的值
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
        $id=empty($_GET['id'])?0:$_GET['id'];
        $sql="select * from cate where pid=$id";
        $result=mysqli_query($link,$sql);
        while ($arr=mysqli_fetch_assoc($result)) {
            $cate[]=$arr;
            # code...
        }
        echo json_encode($cate);die;
    }



//获取三维数组内容是该条新闻所有的同级和父级
    $id=empty($_GET['id'])?'':$_GET['id'];
    $sql="select * from `cate` where `id`=$id";

    $result=mysqli_query($link,$sql);

    $data=mysqli_fetch_assoc($result);
    //获取编辑pid
    $pid=$data;
    //传给函数pid的值
    $cate=eidtCate($pid);
    $cate=array_reverse($cate,true);



    //获取同级和父级的函数
    function eidtCate($pid=array(),$cate=array()){
        //查询同级的新闻
        $sql="select * from `cate` where `pid`=$pid[pid]";
        $result=mysqli_query($GLOBALS['link'],$sql);
        //循环保存到$cate数组里面去
        while( $arr = mysqli_fetch_assoc($result) ){

            $cate[$pid['id']][]= $arr;

        }

        //如果pid不等于0
        if($pid['pid']!=0){
            //查找本身的父级且执行函数本身
            $sql="select * from `cate` where `id`=$pid[pid]";
            $result=mysqli_query($GLOBALS['link'],$sql);
            $data=mysqli_fetch_assoc($result);
            $cate=eidtCate($data,$cate);
        }
        return $cate;
    }
     //print_r($cate);die;
     //print_r ($cate['0']);die;
    include(VIEW_PATH.$admin.'layout.html');

?>